package smlab.view.ui.checkBox
{
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	[Event(name="select",type="flash.events.Event")]
	
	/**
	 * CheckBox
	 * @author simon
	 * 2010.7.13
	 * 
	 */
	public class CheckBox_SM extends Sprite
	{
		private var _btnArr:Array;
		private var _data:Array;
		private var _selectedIndex:int=-1;//选中项索引，从0开始，小于0为未选中
		private var _selectedData:Object;//选中项的数据
		
		public function CheckBox_SM(btnMovieClipArr:Array=null,data:Array=null)
		{
			super();
			_btnArr=[];
			_selectedData=null;
			btns=btnMovieClipArr;
			this.data=data;
		}
		
		/**
		 * 设置所有按钮
		 * 按钮要求：必须是movieClip，有两帧，第一帧是未选中状态，第二帧是选中状态
		 * @param movieClipArr
		 * 
		 */
		public function set btns(movieClipArr:Array):void
		{
			_btnArr=movieClipArr;
			
			for(var i:int=0;i<_btnArr.length;i++){
				var b:MovieClip=_btnArr[i];
				b.gotoAndStop(1);
				b.mouseEnabled=true;
				b.buttonMode=true;
				b.selected=false;
				b.addEventListener(MouseEvent.CLICK,onClick);
			}
			
			if(_data){
				data=_data;
			}
		}
		
		public function get btns():Array
		{
			return _btnArr;
		}
		
		public function set data(data:Array):void
		{
			_data=data;
			
			if(_data){
				if(_btnArr){
					for(var i:int=0;i<_btnArr.length;i++){
						var b:MovieClip=_btnArr[i];
						b.data=_data[i];
					}
				}
			}
			
			_selectedIndex=-1;
		}
		
		public function get data():Array
		{
			return _data;
		}
		
		public function set selectedIndex(index:int):void
		{
			if(index<0){
				if(_btnArr){
					btns=_btnArr;
				}
			}else if(index<_btnArr.length){
				for(var i:int=0;i<_btnArr.length;i++){
					var b:MovieClip=_btnArr[i];
					if(i==index){
						b.gotoAndStop(2);
						b.selected=true;
						_selectedIndex=index;
						_selectedData=_data[index];
					}else{
						b.gotoAndStop(1);
						b.selected=false;
					}
				}
			}
		}
		
		public function get selectedIndex():int
		{
			return _selectedIndex;
		}
		
		public function get selectedData():Object
		{
			return _selectedData;
		}
		
		private function onClick(e:MouseEvent):void
		{
			var m:MovieClip=e.currentTarget as MovieClip;
			
			for(var i:int=0;i<_btnArr.length;i++){
				var b:MovieClip=_btnArr[i];
				
				b.gotoAndStop(1);
				
				if(b==m){
					_selectedIndex=i;
					_selectedData=b.data;
					b.selected=true;
					b.gotoAndStop(2);
				}else{
					b.selected=false;
				}
			}
			
			dispatchEvent(new Event(Event.SELECT));
		}
	}
}